import React, { Component } from 'react';
import _ from 'lodash';
import moment from 'moment';
import {
  Text,
  View,
  DatePickerAndroid,
  TimePickerAndroid,
  TouchableOpacity
} from 'react-native';
import styles from '../styles';
import { parseErrors } from '../..';
import StatusIcon from '../../statusIcon';
import SelectValue from '../selectValue';

export default class DateSelecter extends Component {
  constructor(props) {
    super();
    this.state = {
      value: props.initialValue || '',
      tempValue: '',
      initialValue: props.initialValue,
      valueSize: {}
    };
  }
  componentWillReceiveProps(next) {
    if (next.value !== this.props.value) {
      this.setState(
        {
          value: next.value
        },
        () => {
          if (_.isFunction(this.props.afterChange)) {
            this.props.afterChange(next.value);
          }
        }
      );
    }
  }
  onChange = value => {
    this.props.onChange(value);
  };
  onLayout = e => {
    const {
      nativeEvent: {
        layout: { width, height }
      }
    } = e;
    this.setState({
      valueSize: { width, height }
    });
  };
  pressHandle = async function() {
    const dateValue = this.state.value || new Date();
    const [date, _hour, _minute] = moment
      .utc(dateValue)
      .format('YYYY-MM-DD,HH,mm')
      .split(',');
    try {
      const { action, year, month, day } = await DatePickerAndroid.open({
        date: new Date(date.split('-')),
        minDate: this.props.minDate,
        maxDate: this.props.maxDate,
      });
      if (action !== DatePickerAndroid.dismissedAction) {
        const dateStringfy = `${year}-${month + 1}-${day}`;
        if (this.props.mode !== 'datetime') {
          this.onChange(dateStringfy);
        } else {
          const {
            action: timeAction,
            hour,
            minute
          } = await TimePickerAndroid.open({
            hour: parseInt(_hour, 10),
            minute: parseInt(_minute, 10),
            is24Hour: this.props.is24Hour
          });
          if (timeAction !== TimePickerAndroid.dismissedAction) {
            const timeStringfy = `${hour < 10 ? `0${hour}` : hour}:${
              minute < 10 ? `0${minute}` : minute
            }`;
            this.onChange(`${dateStringfy} ${timeStringfy}`);
          }
        }
      }
    } catch ({ code, message }) {}
  };
  render() {
    return (
      <View style={styles.wrap}>
        <View style={styles.label}>
          <Text style={this.props.error && styles.errorLabel}>
            {this.props.label}
          </Text>
        </View>
        <View style={styles.value} onLayout={this.onLayout}>
          <SelectValue
            value={this.state.value}
            placeholder={this.props.placeholder}
            fn={value => value.toString()}
          />
          <TouchableOpacity
            style={[
              styles.pickerEmiter,
              {
                width: this.state.valueSize.width,
                height: this.state.valueSize.height
              }
            ]}
            onPress={this.pressHandle.bind(this)}
          />
        </View>
        {this.props.error ? (
          <StatusIcon type="error" msg={parseErrors(this.props.error)} />
        ) : null}
      </View>
    );
  }
}
